import { useState, useEffect } from "react"
import { Menu, Button } from "antd"
import { HomeOutlined, ClusterOutlined, UserOutlined, MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons'
import { useLocation, useNavigate } from 'react-router-dom'

// 根据地址获取对应的KEY
const queryKey = (pathname) => {
    let [key] = pathname.match(/\/[^/]+/) || ['/home']
    return key
}

const MenuAgain = function MenuAgain() {
    const location = useLocation(),
        navigate = useNavigate()
    const menuItem = [{
        key: '/home',
        label: '控制面板',
        icon: <HomeOutlined />
    }, {
        key: '/category',
        label: '分类管理',
        icon: <ClusterOutlined />
    }, {
        key: '/personal',
        label: '个人中心',
        icon: <UserOutlined />
    }]

    let [collapsed, setCollapsed] = useState(false),
        [keys, setKeys] = useState(() => {
            let key = queryKey(location.pathname)
            return [key]
        })

    // 监听路由跳转
    useEffect(() => {
        let key = queryKey(location.pathname)
        setKeys([key])
    }, [location])

    // 点击的时候执行
    const handle = ({ key }) => {
        let curKey = queryKey(location.pathname)
        if (key === curKey) return
        navigate(key)
        setKeys([key])
    }

    return <div className="menu-box">
        <Button type="primary"
            onClick={() => {
                setCollapsed(!collapsed)
            }}>
            {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </Button>
        <Menu mode="inline" theme="dark"
            items={menuItem}
            selectedKeys={keys}
            inlineCollapsed={collapsed}
            onClick={handle} />
    </div>
}
export default MenuAgain